#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__
#include <iostream>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "UdpServer.hpp"
#include "MyPthread/Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

using namespace LogMoudule;

const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1"; // 表示本地主机
using func_t = std::function<std::string(const std::string&)>;


class UdpServer
{
private:
public:
    UdpServer(func_t func,uint16_t port = server_port)
        : _sockfd(gsockfd), _server(port),_func(func), _isrunning(false)
    {
    }
    ~UdpServer()
    {
    }
    // 1. 创建socket
    void InitServer()
    {
        // 1. 创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);

        // bind绑定
        int rn = ::bind(_sockfd, CONV(_server.NetAddr()), _server.NetAddrLen());
        if (rn < 0)
        {
            LOG(LogLevel::FATAL) << "bind failed";
            Die(1);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void Start()
    {
        _isrunning = false;
        // 2.2 对端地址，定义对端数据结构
        struct sockaddr_in peer;
        while (true)
        {
            socklen_t len = sizeof(peer);

            char buffer[1024];
            int n = ::recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&peer), &len);

            if (n > 0)
            {
                InetAddr client(peer);


                buffer[n] = 0;
                // LOG(LogLevel::INFO) << "recvfrom:" << buffer;

                // std::string echo_string = "echo# ";
                // echo_string += buffer;

                std::string result = _func(buffer);
                LOG(LogLevel::INFO) <<"|"<<buffer <<"|"<<result;

                ::sendto(_sockfd, result.c_str(), result.size(), 0, CONV(client.NetAddr()), client.NetAddrLen());
            }
            else
            {
                LOG(LogLevel::INFO) << "recv nothing";
            }
        }
        _isrunning = false;
    }

private:
    int _sockfd;
    InetAddr _server;
    // InetAddr _client;
    bool _isrunning; // 服务器运行状态

    // 业务
    func_t _func;

};

#endif